﻿Imports System.Data
Imports System.Data.SqlClient

Public Class AsyncQueryExample
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub ExecuteAsyncQueries()
        Dim connectionStringPubs As String = "server=localhost;async=true;uid=sa;pwd=thiru;database=pubs;"
        Dim connectionStringNorthwind As String = "server=localhost;async=true;uid=sa;pwd=thiru;database=northwind;"
        'Define two connection objects, one for each database
        Using connPubs As New SqlConnection(connectionStringPubs)
            Using connNorthwind As New SqlConnection(connectionStringNorthwind)
                'Open the first connection
                connPubs.Open()
                'Start the execution of the first query 
                Dim commandAuthors As New SqlCommand("Select au_id, au_fname from Authors", connPubs)
                commandAuthors.CommandType = CommandType.Text
                Dim startTime As DateTime = DateTime.Now()
                Dim arAuthors As IAsyncResult = commandAuthors.BeginExecuteReader()
                'Open the second connection
                connNorthwind.Open()
                'Start the execution of the second sql query
                Dim commandEmployees As New SqlCommand("Select EmployeeID, FirstName from Employees", connNorthwind)
                Dim arEmployees As IAsyncResult = commandEmployees.BeginExecuteReader()
                'Both queries are executing at the same time
                'Now wait for the first query to complete execution
                Dim readerAuthors As SqlDataReader = commandAuthors.EndExecuteReader(arAuthors)
                Dim readerEmployees As SqlDataReader = commandEmployees.EndExecuteReader(arEmployees)
                Dim endTime As DateTime = DateTime.Now()
                While (readerAuthors.Read())
                    lstAuthors.Items.Add(readerAuthors("au_fname"))
                End While
                While (readerEmployees.Read())
                    lstEmployees.Items.Add(readerEmployees("FirstName"))
                End While
                lblAsyncResult.Text = " It took " & (endTime.Millisecond - startTime.Millisecond).ToString() & " milliseconds to execute both queries asynchronously"
            End Using
        End Using
    End Sub

    Private Sub btnExecute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExecute.Click
        ExecuteAsyncQueries()
    End Sub
End Class
